package SecondeStage.Collection.Set;

import java.util.HashSet;
import java.util.Objects;

public class HashSetExercise {
    public static void main(String[] args) {
        HashSet hashSet =new HashSet();
        // 如果不重写equals和hashCode方法，这4个对象都能添加成功，因为他们是4个不同的对象，其hashcode值不同
        // 重写equals和hashCode方法
        hashSet.add(new employee("milan",18)); // ok
        hashSet.add(new employee("smith",28)); // ok
        hashSet.add(new employee("milan",23)); // ok
        hashSet.add(new employee("milan",18)); // no , 此时hashCode值相同，不能添加

        System.out.println(hashSet);
    }
}

class employee{
    private String name;
    private int age;

    public employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 重写equals，当name和age都相同时，equals结果返回true
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        employee employee = (employee) o;
        return age == employee.age && Objects.equals(name, employee.name);
    }
    // 重写hashCode，当name和age都相同时,返回相同的hashCode
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
